package com.xsm.activitygroup;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.xsm.activitygroup.R;
import com.xsm.activitygroup.activity2.GetNewData;
import com.xsm.adapter.MessageAdapter;
import com.xsm.internet.ConnectUrl;
import com.xsm.internet.PostMessage;
import com.xsm.object.BookObject;
import com.xsm.view.LoadDialog;
import com.xsm.view.Mydialog;

import android.R.integer;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class BookMessage extends Activity{
	TextView bookid,bookname,price,place,booktype,press,oner,time,message,phone,author;
	BookObject ms;
	LinearLayout userLayout,otherLayout;
	String userString;
	MyHandler handler;
	Activity context;
	LoadDialog dialog;
	String typeString="";
	PullToRefreshScrollView  scrollview;
	LinearLayout imagelayout;
	ArrayList<Bitmap> arrayList=new ArrayList<Bitmap>(); 
	private static int  REFRESHING=0;
	ArrayList<String> pathList=new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.bookmessage);
	 context=this;
	 ms=(BookObject)getIntent().getExtras().get("ms");
	 typeString=getIntent().getExtras().getString("type");
	 SharedPreferences sharedPreferences=getSharedPreferences("XSM", 0);
	 userString=sharedPreferences.getString("User", "");
	 handler=new MyHandler();
     initview();
     new LoadMessage().execute();
}
protected void onResume() {
	MobclickAgent.onResume(this);
	super.onResume();
}
protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
}


private void initview(){
	
	imagelayout=(LinearLayout)findViewById(R.id.imagelayout);
	userLayout=(LinearLayout)findViewById(R.id.user);
	otherLayout=(LinearLayout)findViewById(R.id.other);
	scrollview=(PullToRefreshScrollView)findViewById(R.id.loadMessage);
	
	if(ms.getUserid().equals(userString)){
		if(typeString.equals("hadsell")){
			otherLayout.setVisibility(View.GONE);
			userLayout.setVisibility(View.GONE);	
		}else {
			otherLayout.setVisibility(View.GONE);
			userLayout.setVisibility(View.VISIBLE);
		}
	}
	else {
	
			otherLayout.setVisibility(View.VISIBLE);
			userLayout.setVisibility(View.GONE);		
	}
	
	
	bookid=(TextView)findViewById(R.id.bookid);
	phone=(TextView)findViewById(R.id.phone);
	author=(TextView)findViewById(R.id.author);
	bookname=(TextView)findViewById(R.id.bookname);
	place=(TextView)findViewById(R.id.place);
	price=(TextView)findViewById(R.id.price);
	booktype=(TextView)findViewById(R.id.booktype);
	oner=(TextView)findViewById(R.id.oner);
	time=(TextView)findViewById(R.id.btime);
	press=(TextView)findViewById(R.id.press);
	message=(TextView)findViewById(R.id.message);
	
	
	String s=ms.getTime().replaceAll("-","");
	String goodsid=ms.getGoodsid();
	for(int i=0;i<(8-goodsid.length());i++){
		goodsid="0"+goodsid;
	}
	
	bookid.setText(s+goodsid);
	bookname.setText(ms.getBookName());
	price.setText("￥"+ms.getPrice()+"元");
	place.setText(ms.getPlace());
	booktype.setText(ms.getBookType());
	press.setText(ms.getPress());
	time.setText(ms.getTime());
	message.setText(ms.getMessage());
	phone.setText(ms.getPhone());
	oner.setText(ms.getOner());
	author.setText(ms.getAuthor());
	
	scrollview.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
		public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
			String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
					DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			if(REFRESHING==0)
	      new  LoadMessage().execute(); 
		}
	});
	
//	String spath[]=ms.getPath().split(";");
//	int plength=spath.length;
//if(ms.getPath().equals("")){
//	imagelayout.setVisibility(View.GONE);
//}else {
//	for(int i=0;i<plength;i++){
//		final ImageView imageView=new ImageView(this);
//		imageView.setBackgroundResource(R.drawable.bg1);
//		LinearLayout.LayoutParams layoutParams=new LayoutParams(120,120);
//		layoutParams.setMargins(10, 0, 10, 0);
//		imageView.setLayoutParams(layoutParams);	
//	    imagelayout.addView(imageView);
//	}	
//}
}

public void Back(View view){
finish();
}

public void Phone(View view){
	Intent intent=new Intent();
	intent.setAction(Intent.ACTION_DIAL);   //android.intent.action.DIAL
	intent.setData(Uri.parse("tel:"+ms.getPhone()));
	startActivity(intent);
}

public void Message(View view){
	Uri smsToUri = Uri.parse("smsto:"+ms.getPhone());
	Intent mIntent = new Intent( android.content.Intent.ACTION_SENDTO, smsToUri );
	startActivity( mIntent );
}

//public void Lianxi(View view){
//	DisplayMetrics dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);
//int	width = dm.widthPixels;
//	 View layout=LayoutInflater.from(context).inflate(R.layout.calllayout, null);
//	 Button bt1=(Button)layout.findViewById(R.id.phonec);
//	 Button bt2=(Button)layout.findViewById(R.id.messagec);
//	 bt1.setOnClickListener(new OnClickListener() {
//		public void onClick(View v) {
//			Intent intent=new Intent();
//			intent.setAction(Intent.ACTION_DIAL);   //android.intent.action.DIAL
//			intent.setData(Uri.parse("tel:"+ms.getPhone()));
//			startActivity(intent);
//		}
//	});
//	 bt2.setOnClickListener(new OnClickListener() {
//		public void onClick(View v) {
//			Uri smsToUri = Uri.parse("smsto:"+ms.getPhone());
//			Intent mIntent = new Intent( android.content.Intent.ACTION_SENDTO, smsToUri );
//			startActivity( mIntent );
//		}
//	});
//	   PopupWindow      popupWindow = new PopupWindow(this);
//	         popupWindow.setHeight(190);
//	         popupWindow.setWidth(width);
//	         popupWindow.setBackgroundDrawable(new ColorDrawable(Color.argb(200, 40, 39, 39)));
//	         popupWindow.setOutsideTouchable(true);
//	         popupWindow.setFocusable(true);
//	         popupWindow.setContentView(layout);
//	         popupWindow.showAsDropDown(view,0,10);
//}


public void OutGood(View view){
	WindowManager m = context.getWindowManager();  
    Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
    WindowManager.LayoutParams p = context.getWindow().getAttributes(); // 获取对话框当前的参数值
   p.height = (int) (d.getHeight() * 0.4); // 高度设置为屏幕的0.6
    p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.95
   // Log.d("my", p.height+"h"+p.width);
	
	
Mydialog mydialog=new Mydialog(BookMessage.this, "下架的商品将不会出现在商场上,商品下架后将返回一半的金豆,是否继续操作?");
mydialog.settitle("下架商品");
mydialog.setEnsureText("确定");
//mydialog.setParams(p);
mydialog.setEnsurelistener(new OnClickListener() {
		public void onClick(View v) {
			dialog=new LoadDialog(context,"操作中,请稍候...");
			dialog.showDialog();
			new Thread(new Runnable() {
				public void run() {
					List params=new ArrayList();
					params.add(new BasicNameValuePair("ASK","Outgoods"));
					params.add(new BasicNameValuePair("goodsid",ms.getGoodsid()));
					PostMessage postMessage=new PostMessage(params);
					String result=postMessage.getResult();
					Message msg=handler.obtainMessage();
					if(result.equals("1"))
					msg.what=1;
					else {
					msg.what=2;	
					}
					handler.sendMessage(msg);
				}
			}).start();	
		}
	});
mydialog.showDialog();
}

class MyHandler extends Handler{
	public void handleMessage(Message msg) {
		if(msg.what==1)
		{
	Toast.makeText(context, "商品下架成功", Toast.LENGTH_LONG).show();	
	Intent intent=new Intent();
	intent.putExtra("index", getIntent().getExtras().getInt("index"));
	setResult(RESULT_OK, intent);
	finish();
	}else if(msg.what==2){
	if(dialog!=null)
	dialog.dissmissDialog();	
	Toast.makeText(context, "操作失败,请检查网络配置", Toast.LENGTH_LONG).show();		
	}else if(msg.what==3){
		Toast.makeText(context, "商品收藏成功", Toast.LENGTH_LONG).show();		
	}
		if(dialog!=null)
		dialog.dissmissDialog();
		super.handleMessage(msg);
	}
}


class LoadMessage extends AsyncTask<Void, Void, String>{
	protected String doInBackground(Void... params) {
		REFRESHING=1;
		String path="";
		List param=new ArrayList();
		param.add(new BasicNameValuePair("ASK","GetBookDetailMessage"));
		param.add(new BasicNameValuePair("goodsid",ms.getGoodsid()));
		PostMessage postMessage=new PostMessage(param);
		String result=postMessage.getResult();
	   try {
		JSONObject object=new JSONObject(result);
		if(!result.equals("-1")){
			arrayList.clear();
			pathList.clear();
			ms.setOner(object.getString("username"));
			ms.setPhone(object.getString("issuephone"));
			ms.setMessage(object.getString("bookmessage"));
			
//			path=array.optJSONObject(0).getString("path");	
//			 String s[]=path.split(";");
//			 String url=new ConnectUrl().uString;
//		     for(int i=0;i<s.length;i++){
//			 Bitmap bitmap=loadImageFromUrl(url+"/XSMService"+"/Photos"+s[i],80);
//			  arrayList.add(bitmap);
//			  pathList.add(url+"/XSMService"+"/Photos"+s[i]);
	//	 }
		}
	  } catch (JSONException e) {
	     Log.d("my",e+"");
	 }
	 
	   
	   return result;
	}
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		REFRESHING=0;
		scrollview.onRefreshComplete();
		if(!result.equals("-1")){
		phone.setText(ms.getPhone());
		oner.setText(ms.getOner());
		message.setText(ms.getMessage());
//		 imagelayout.removeAllViews();
//		for(int i=0;i<arrayList.size();i++){
//			final ImageView imageView=new ImageView(context);
//			imageView.setImageBitmap(arrayList.get(i));
//			LinearLayout.LayoutParams layoutParams=new LayoutParams(120,120);
//			layoutParams.setMargins(10, 0, 10, 0);	
//			imageView.setLayoutParams(layoutParams);
//			imageView.setTag(pathList.get(i));
//			imageView.setOnClickListener(new OnClickListener() {
//				public void onClick(View arg0) {	
//Intent intent=new Intent();
//intent.putExtra("path",imageView.getTag().toString());
//intent.setClass(context, PhotoView.class);
//startActivity(intent);
//				}
//			});
//			imagelayout.addView(imageView);
//		}
		}
	}
}






public static Bitmap loadImageFromUrl(String url, int sc)
{

    URL m;
    InputStream i = null;
    BufferedInputStream bis = null;
    ByteArrayOutputStream out = null;
byte[] isBuffer=new byte[1000];
    if (url == null)
        return null;
    try
    {
        m = new URL(url);
        i = (InputStream) m.getContent();
        bis = new BufferedInputStream(i, 1024 * 4);
        out = new ByteArrayOutputStream();
        int len = 0;

        while ((len = bis.read(isBuffer)) != -1)
        {
            out.write(isBuffer, 0, len);
        }
        out.close();
        bis.close();
    } catch (MalformedURLException e1)
    {
        e1.printStackTrace();
        return null;
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    if (out == null)
        return null;
    byte[] data = out.toByteArray();
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, 0, data.length, options);
    options.inJustDecodeBounds = false;
    int be = (int) (options.outHeight / (float) sc);
    if (be <= 0)
    {
        be = 1;
    } else if (be > 3)
    {
        be = 3;
    }
    options.inSampleSize = be;
    Bitmap bmp =null;
    try
    {
        bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options); //返回缩略图
    } catch (OutOfMemoryError e)
    {
        System.gc();
        bmp =null;
    }
    return bmp;
}



}
